package com.demo.ssy.model;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import com.demo.ssy.kit.StrKit;

public class ModelInjector {

	@SuppressWarnings("unchecked")
	public static <T> T inject(Class<?> modelClass, HttpServletRequest request,
			boolean skipConvertError) {
		String modelName = modelClass.getSimpleName();
		return (T) inject(modelClass, StrKit.firstCharToLowerCase(modelName),
				request, skipConvertError);
	}

	public static final <T> T inject(Class<?> modelClass, String modelName,
			HttpServletRequest request, boolean skipConvertError) {
		Object model = null;
		try {
			model = modelClass.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		injectCommonModel(model, modelName, request, modelClass,
				skipConvertError);
		return (T) model;
	}

	private static final void injectCommonModel(Object model, String modelName,
			HttpServletRequest request, Class<?> modelClass,
			boolean skipConvertError) {
		Method[] methods = modelClass.getMethods();
		for (Method method : methods) {
			String methodName = method.getName();
			if (!methodName.startsWith("set")) // only setter method
				continue;

			Class<?>[] types = method.getParameterTypes();
			if (types.length != 1) // only one parameter
				continue;

			String attrName = methodName.substring(3);
			String value = request.getParameter(StrKit
					.firstCharToLowerCase(attrName));
			if (value != null) {
				try {
					method.invoke(model, TypeConverter.convert(types[0], value));
				} catch (Exception e) {
					// if (skipConvertError == false)
					throw new RuntimeException(e);
				}
			}
		}
	}
}
